package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.common.CarApp;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.utils.SPUtils;
import com.parking.carsystem.parkingchargesystem.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.login_text)
    TextView loginText;
    @BindView(R.id.big_login_text)
    RelativeLayout bigLoginText;
    @BindView(R.id.tips_text)
    TextView tipsText;
    @BindView(R.id.id_act_username)
    EditText idActUsername;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.verification_code)
    TextView verificationCode;
    @BindView(R.id.layout1)
    RelativeLayout layout1;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.line1)
    View line1;
    @BindView(R.id.layout2)
    RelativeLayout layout2;
    @BindView(R.id.input)
    RelativeLayout input;
    @BindView(R.id.login)
    TextView login;
    @BindView(R.id.login_meathed)
    TextView loginMeathed;
    //默认密码登录
    boolean loginMeathedStatus;
    @BindView(R.id.choose_text)
    ImageView chooseText;
    @BindView(R.id.agreement)
    TextView agreement;
    @BindView(R.id.privacy)
    TextView privacy;
    private int time = 120;
    private boolean codeStatus = true;
    private String phoneName;
    private String phone;
    private String captcha;
    private boolean isLogin = true;
    private boolean isChoosePrivacy;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        verificationCode.setOnClickListener(this);
        login.setOnClickListener(this);
        loginMeathed.setOnClickListener(this);
        chooseText.setOnClickListener(this);
        agreement.setOnClickListener(this);
        privacy.setOnClickListener(this);
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (loginMeathedStatus && !TextUtils.isEmpty(phone)) {
                    settingVerfication();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        login.setOnClickListener(this);
    }

    @Override
    public void initData() {
        String userName = SPUtils.getInstance(this).getString(Constant.USERNAME);
        String password1 = SPUtils.getInstance(this).getString(Constant.PASSWORD);
        idActUsername.setText(userName);
         isChoosePrivacy = SPUtils.getInstance(this).getBoolean(Constant.CHOOSE_PRIVACY);
        if (isChoosePrivacy) {
            chooseText.setImageResource(R.mipmap.selected);
        }else {
            chooseText.setImageResource(R.mipmap.unselected);
        }
        if (!loginMeathedStatus) {
            password.setText(password1);
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.login://登录
                if (!isChoosePrivacy) {
                    showToast("请点击同意隐私协议");
                    return;
                }
                if (isLogin) {
                    isLogin = false;
                    String userName = idActUsername.getText().toString().trim();
                    String passwordl = password.getText().toString().trim();
                    if (TextUtils.isEmpty(userName) || !Utils.isHandset(userName)) {
                        showToast("请输入正确的手机号");
                        return;
                    }
                    if (loginMeathedStatus) {
                        if (TextUtils.isEmpty(passwordl)) {
                            showToast("请输入验证码");
                            return;
                        }
                    } else {
                        if (TextUtils.isEmpty(passwordl)) {
                            showToast("请输入密码");
                            return;
                        }
                    }
                    phone = idActUsername.getText().toString().trim();
                    captcha = password.getText().toString().trim();
                    showLoading();
                    HashMap<String, String> hashMap = new HashMap<>();
                    if (loginMeathedStatus) {
                        hashMap.put("phone", phone);
                        hashMap.put("captcha", captcha);
                        JSONObject jsonObject = new JSONObject(hashMap);
                        OkGo.<String>post(Constant.url + Constant.LOGIN)
                                .upJson(jsonObject.toString())
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        stopLoading();
                                        isLogin = true;
                                        startMainActivity(response);
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        isLogin = true;
                                        showToast(response.message());
                                        stopLoading();
                                    }
                                });
                    } else {
                        hashMap.put("phone", phone);
                        hashMap.put("password", Utils.digest(captcha));
                        JSONObject jsonObject = new JSONObject(hashMap);
                        OkGo.<String>post(Constant.url + Constant.PWLOGIN)
                                .upJson(jsonObject.toString())
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        stopLoading();
                                        isLogin = true;
                                        startMainActivity(response);
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        isLogin = true;
                                        showToast(response.message());
                                        stopLoading();
                                    }
                                });
                    }
                }
                break;
            case R.id.verification_code:
                phoneName = idActUsername.getText().toString().trim();
                if (codeStatus) {
                    //获取验证码
                    getVerificationCode();
                }
                break;
            case R.id.login_meathed:
                //更换登录方式
                if (loginMeathedStatus) {
                    settingVerfication();
                    password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    loginMeathedStatus = false;
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    verificationCode.setVisibility(View.GONE);
                    loginMeathed.setText("使用验证码登录");
                    password.setHint(getResources().getString(R.string.password));
                } else {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    password.setInputType(InputType.TYPE_CLASS_PHONE);
                    loginMeathedStatus = true;
                    verificationCode.setVisibility(View.VISIBLE);
                    loginMeathed.setText("使用密码登录");
                    password.setHint(getResources().getString(R.string.verification_code));
                }
                break;
            case R.id.choose_text:
                if (isChoosePrivacy) {
                    isChoosePrivacy = false;
                    chooseText.setImageResource(R.mipmap.unselected);
                }else {
                    isChoosePrivacy = true;
                    chooseText.setImageResource(R.mipmap.selected);
                }
                SPUtils.getInstance(this).put(Constant.CHOOSE_PRIVACY,isChoosePrivacy);
                break;
            case R.id.agreement:
                intent = new Intent(this,PrivacyAgreementActivity.class);
                intent.putExtra(Constant.CHOOSE_PRIVACY,true);
                startActivity(intent);
                break;
            case R.id.privacy:
                intent = new Intent(this,PrivacyAgreementActivity.class);
                intent.putExtra(Constant.CHOOSE_PRIVACY,false);
                startActivity(intent);
                break;
        }
    }

    private void getVerificationCode() {
        showLoading();
        if (!TextUtils.isEmpty(phoneName)) {
            OkGo.<String>get(Constant.url + Constant.CAPTCHAPHONE)
                    .params("phone", phoneName)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            stopLoading();
                            if (codeStatus) {
                                codeStatus = false;
                                //延时一秒的消息
                                handler.sendEmptyMessageDelayed(100, 1000);
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            stopLoading();
                            if (codeStatus) {
                                codeStatus = false;
                                //延时一秒的消息
                                handler.sendEmptyMessageDelayed(100, 1000);
                            }
                        }
                    });
        } else {
            showToast("请输入手机号");
        }
    }

    private void startMainActivity(Response<String> response) {
        try {
            JSONObject jsonObject1 = new JSONObject(response.body());
            int code = jsonObject1.getInt("code");
            if (code == 200) {
                if (!loginMeathedStatus) {
                    SPUtils.getInstance(LoginActivity.this).put(Constant.USERNAME, phone);
                    SPUtils.getInstance(LoginActivity.this).put(Constant.PASSWORD, captcha);
                }
                String data = jsonObject1.getString("data");
                CarApp.okGo.addCommonHeaders(new HttpHeaders("Authorization", "Bearer " + data));
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                showToast(response.message());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void handleMessageMeathed(Message msg) {
        if (msg.what == 100) {
            if (time > 0) {
                time--;//减去一秒
                verificationCode.setText("倒计时" + time + "秒");
                handler.sendEmptyMessageDelayed(100, 1000);
            } else {
                settingVerfication();
            }
        }
    }

    private void settingVerfication() {
        //清除发送的延时消息
        handler.removeCallbacksAndMessages(null);
        codeStatus = true;
        time = 120;
        verificationCode.setText("获取验证码");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将结果转发给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
